#!/usr/bin/python  
#coding=utf-8 
import webbrowser
from weibo import APIClient

class SmartWeibo:
      client = None
      APP_KEY='2869726294'
      APP_SECRET='f0648a6118aba93ea6b669a06c63038b'
      CALLBACK_URL='http://www.chinaunix.net/'
      r = None
      recent_ids = ['','','','','']
      ids_used = [0, 0, 0, 0, 0]
      cache_size = 5

      def init(self):        
            self.client = APIClient(app_key=self.APP_KEY, app_secret=self.APP_SECRET, redirect_uri=self.CALLBACK_URL)
            url = self.client.get_authorize_url().replace('%3A' , ':')
            webbrowser.open(url)
            code = raw_input('input your code:')
            self.r = self.client.request_access_token(code)
            access_token = self.r.access_token
            expires_in = self.r.expires_in
            self.client.set_access_token(access_token, expires_in)

      def PostStatus(self, text):
            self.client.post.statuses__update(status=text)

      def UpdateCache(self):
            self.r = self.client.get.statuses__mentions(count=self.cache_size)
            #self.statuses = r.statuses
	    for i in range(0, self.cache_size):
		index = self.FindIdIndex(self.r.statuses[i].id)
		if index == self.cache_size:
			self.recent_ids.insert(0, self.r.statuses[i].id)
			self.recent_ids.pop()
			self.ids_used.insert(0, 0)
			self.ids_used.pop()
		else:
			return


      def GetMostRecentStatus(self):
	    if self.ids_used[0] == 0:
		self.ids_used[0] = 1
	    	return self.r.statuses[0].text.encode("utf-8")
	    else:
		return 'Have been used'


      def GetNRecentStatus(self, n):
	    if self.ids_used[n] == 0:
		self.ids_used[n] = 1
	   	return self.r.statuses[n].text.encode("utf-8")
	    else:
		return 'Have been used'

      def FindIdIndex(self, integer):
	    for i in range(0, self.cache_size):
		if self.recent_ids[i] == integer:
			return i
	    return self.cache_size


